from contextlib import contextmanager
from typing import Union
from database import SessionLocal
from fastapi import APIRouter, Depends, HTTPException, Query

import sys
from typing import List
from config.logging import logger
from services.database_manager import databaseManager
from services.auth_handler import AuthHandler
from datetime import datetime, timedelta
import json
from services.api.third_api_service import ThirdApiService
from sqlalchemy.orm import Session
from database import SessionLocal
from services.database_manager import databaseManager
from models.red_book_chat_logs import RedBookChatLog

# 定义服务类
third_api_service = ThirdApiService()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


class XhsHandlerService:
    async def text_to_json(self, websocket, content: str):
        system_user = "文灵助手"
        content_json = json.loads(content)
        print(f"接收到的消息：{content_json.get('message')},type:{type(content_json)}")
        message = await third_api_service.disable_text_check(websocket, content)
        # {"message": full_response, "chat": content_json}
        res = {'username': system_user, 'message': message['message']}
        addData = await self.userContentHandle(message)
        return res

    async def userContentHandle(self, content):
        """
        将字符串转换为json,记录用户发送的消息
        """
        # 使用生成器获取数据库会话
        db_session_generator = get_db()
        db = next(db_session_generator)
        try:
            condition = {
                "message": content['message'],
                "user_uuid": content['chat']['user_id'],
                "chat": content['chat']['message'],
                "type": 1
            }
            print(f"用户发送的消息：{condition}")
            # 直接使用数据库会话进行操作
            new_entry = RedBookChatLog(**condition)
            db.add(new_entry)
            db.commit()
        except Exception as e:
            db.rollback()
            logger.error(f"Error: {e}")
            raise e
        finally:
            # 确保关闭数据库会话
            db.close()

        # try:
        #     db_manager = databaseManager(get_db)
        #     condition = {
        #         "message": content['message'],
        #         "user_uuid": content['message'].get("user_uuid"),
        #         "chat": content['message'].get('message'),
        #         "type": 1
        #     }
        #     print(f"用户发送的消息：{condition}")
        #     # 写入询问内容与答复写入数据表
        #     db_manager.create_entry(RedBookChatLog, condition)
        #     return True
        # except Exception as e:
        #     return {"error": "转换失败"}
